﻿using GamFi.Admin.API.Application.DefaultSettings;
using GamFi.Admin.API.Domain.Entities;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace GamFi.Admin.API.WEB.Controllers;

[ApiController]
[AllowAnonymous]
[Route("api/[controller]")]
public class AuthController(SignInManager<User> signInManager, UserManager<User> userManager) : ControllerBase
{
    /// <summary>
    /// Логин
    /// </summary>
    /// <param name="password"></param>
    /// <param name="cancellationToken"></param>
    /// <param name="username"></param>
    [HttpPost("Login")]
    public async Task<IActionResult> Login(string username, string password, CancellationToken cancellationToken)
    {
        var result = await signInManager.PasswordSignInAsync(username, password, false, lockoutOnFailure: false);

        if (!result.Succeeded) 
            return Unauthorized("Invalid username or password");
        
        var user = await userManager.FindByNameAsync(username);

        if (user == null) return 
            Unauthorized("Invalid username or password");
        
        if (await userManager.IsInRoleAsync(user, BaseRoles.AdminRoleName))
            return Ok("Login successful as Admin");
        
        return Unauthorized("You are not authorized to login as Admin");
    }

    /// <summary>
    /// Выход
    /// </summary>
    /// <param name="cancellationToken"></param>
    [Authorize]
    [HttpDelete("Logout")]
    public async Task Logout(CancellationToken cancellationToken)
        => await signInManager.SignOutAsync();
}